package br.com.alugargaragem.domain.login.business.impl;

import static br.com.lambdacore.validator.Validator.is;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import br.com.alugargaragem.domain.login.business.LoginBusiness;
import br.com.alugargaragem.domain.login.exception.UserAlreadyRegisteredException;
import br.com.alugargaragem.domain.login.exception.UserNotYetRegisteredException;
import br.com.alugargaragem.domain.login.model.Login;
import br.com.alugargaragem.domain.login.repository.LoginRepository;

@Component("loginBusiness")
public class LoginBusinessBean implements LoginBusiness {

	@Resource
	private LoginRepository loginRepository;

	public Login signin(Login login) {
		login = this.findByEmailPassword(login);
		if (is(login).nil()) {
			this.userNotYetRegistered(login);
		}
		return login;
	}

	public void signup(Login login) {
		this.verifyLoginAlreadyRegistered(login);
		this.save(login);
	}

	private Login findByEmail(Login login) {
		return this.loginRepository.findByEmail(login);
	}

	private Login findByEmailPassword(Login login) {
		return this.loginRepository.findByEmailPassword(login);
	}

	private void save(Login login) {
		this.loginRepository.persist(login);
	}

	private void userAlreadyRegistered(Login login) {
		throw new UserAlreadyRegisteredException(login);
	}

	private void userNotYetRegistered(Login login) {
		throw new UserNotYetRegisteredException(login);
	}

	private void verifyLoginAlreadyRegistered(Login login) {
		Login loginExist = this.findByEmail(login);
		System.out.println(loginExist);
		if (is(loginExist).notNil()) {
			this.userAlreadyRegistered(login);
		}
	}
}
